//
//  HJStatuses.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/24.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

class HJStatuses: NSObject {
    // MARK: - Attribute
    var created_at: String?
    var id: Int64 = 0
    var text: String?
    var reposts_count: Int = 0
    var comments_count: Int = 0
    var attitudes_count: Int = 0
    var rowHeight: CGFloat?
    var source: String? {
        didSet{
            source = source?.sinaSource()
        }
    }
    // 微博配图的NSURL数组.原创微博的配图URL
    var storePictureURLs: [NSURL]?
    
    // 通过分析微博返回的数据 是一个数组,数组里面是一个字典["thumbnail_pic": url]
    /// 图片地址数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            let count = pic_urls?.count ?? 0
            if count == 0 {
                return
            }
            storePictureURLs = [NSURL]()
            for dict in pic_urls! {
                let urlString = dict["thumbnail_pic"] as! String
                let url = NSURL(string: urlString)
                storePictureURLs?.append(url!)
            }
        }
    }
    
    /// 微博模型里面有一个user,用户模型,虽然定义的是HJBlogUser模型,KVC并不会自动将user字典转成模型,会将user原来的内容(字典)赋值user属性
    /// 需要在KVC字典转模型的时候,拦截user这个属性的设置,自己来将字典转成HJBlogUser
    var user: HJBlogUser?
    
    var retweeted_status: HJStatuses?
    
    // Dictionary transfer model
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // setValuesForKeysWithDictionary方法实际上回调用setValue:forKey:
    // setValuesForKeysWithDictionary,获取字典里面的每一个key,调用setValue:forKey:,如果这个key在模型中找不到对应的属性,就调用setValue:forUndefinedKey
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                // 字典转模型,给user赋值
                user = HJBlogUser(dict: dict)
            }
            // 注意:我们拦截这个user,自己字典转模型,赋值给status的user属性,不要让他在调用父类的super.setValue(value, forKey: key)
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = HJStatuses(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
//        HJPrint(msg: "key = \(key)")
    }
    
    override var description: String {
        let keys = ["id", "created_at", "text", "source", "pic_urls", "reposts_count", "comments_count", "attitudes_count", "user"]
        return "\n\t微博模型: \(dictionaryWithValuesForKeys(keys).description)"
    }
}
